import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_fonts/google_fonts.dart';
import 'dart:math' as math;
import 'package:provider/provider.dart';
import '../generated/l10n/app_localizations.dart';
import 'conversation_screen.dart';
import 'language_settings_screen.dart';
import 'settings_screen.dart';
import 'camera_screen.dart';
import '../services/language_service.dart';
import '../services/theme_service.dart';
import 'package:flutter/rendering.dart';

/// 翻译器主界面
///
/// 这是应用程序的主界面，提供文本和语音翻译功能。
/// 界面包含输入区域、语言切换区域、翻译结果区域和底部功能按钮栏。
/// 支持多种输入方式：语音输入、键盘输入、相机拍照识别等。
class TranslatorScreen extends StatefulWidget {
  const TranslatorScreen({super.key});

  @override
  State<TranslatorScreen> createState() => _TranslatorScreenState();
}

class _TranslatorScreenState extends State<TranslatorScreen> {
  // 语音输入状态标志
  bool _isListening = false;
  // 文本输入控制器
  final TextEditingController _textController = TextEditingController();
  // 添加输入文本和翻译结果的状态
  String _inputText = '';
  String _translationResult = '';

  @override
  void dispose() {
    _textController.dispose();
    super.dispose();
  }

  // 清空内容方法
  void _clearContent() {
    setState(() {
      _inputText = '';
      _translationResult = '';
      _textController.clear();
    });
  }

  // 显示输入对话框
  Future<void> _showInputDialog() async {
    final l10n = AppLocalizations.of(context)!;
    final theme = Theme.of(context);
    _textController.clear();

    await showDialog(
      context: context,
      barrierDismissible: true,
      barrierColor: Colors.black.withOpacity(0.5),
      builder: (context) => Align(
        alignment: Alignment.topCenter,
        child: Padding(
          padding: EdgeInsets.only(
            top: MediaQuery.of(context).padding.top + 20,
            left: 16,
            right: 16,
          ),
          child: Material(
            color: Colors.transparent,
            child: Container(
              constraints: BoxConstraints(
                maxHeight: MediaQuery.of(context).size.height * 0.5,
              ),
              decoration: BoxDecoration(
                color: theme.cardColor,
                borderRadius: BorderRadius.circular(16),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.2),
                    blurRadius: 10,
                    offset: const Offset(0, 5),
                  ),
                ],
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(16),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 20,
                        vertical: 12,
                      ),
                      decoration: BoxDecoration(
                        color: theme.colorScheme.surface,
                        border: Border(
                          bottom: BorderSide(
                            color: theme.dividerColor,
                            width: 1,
                          ),
                        ),
                      ),
                      child: Row(
                        children: [
                          Text(
                            l10n.inputHint,
                            style: TextStyle(
                              color: theme.textTheme.bodySmall?.color,
                              fontSize: 14,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                          const Spacer(),
                          Icon(
                            Icons.keyboard,
                            color: theme.textTheme.bodySmall?.color,
                            size: 16,
                          ),
                        ],
                      ),
                    ),
                    Flexible(
                      child: SingleChildScrollView(
                        child: Padding(
                          padding: const EdgeInsets.fromLTRB(20, 16, 20, 20),
                          child: Stack(
                            children: [
                              TextField(
                                controller: _textController,
                                autofocus: true,
                                maxLines: 12,
                                minLines: 8,
                                style: TextStyle(
                                  color: theme.textTheme.bodyLarge?.color,
                                  fontSize: 16,
                                  height: 1.3,
                                ),
                                decoration: InputDecoration(
                                  isDense: true,
                                  contentPadding: const EdgeInsets.fromLTRB(
                                    16,
                                    12,
                                    16,
                                    48, // 增加底部内边距，为按钮留出空间
                                  ),
                                  hintText: l10n.inputHint,
                                  hintStyle: TextStyle(
                                    color: theme.textTheme.bodySmall?.color,
                                    fontSize: 16,
                                  ),
                                  filled: true,
                                  fillColor: theme.colorScheme.surface,
                                  border: OutlineInputBorder(
                                    borderRadius: BorderRadius.circular(12),
                                    borderSide: BorderSide(
                                      color: theme.dividerColor,
                                    ),
                                  ),
                                  enabledBorder: OutlineInputBorder(
                                    borderRadius: BorderRadius.circular(12),
                                    borderSide: BorderSide(
                                      color: theme.dividerColor,
                                    ),
                                  ),
                                  focusedBorder: OutlineInputBorder(
                                    borderRadius: BorderRadius.circular(12),
                                    borderSide: BorderSide(
                                      color: theme.colorScheme.primary,
                                      width: 1.5,
                                    ),
                                  ),
                                ),
                              ),
                              Positioned(
                                right: 8,
                                bottom: 12, // 调整按钮位置
                                child: GestureDetector(
                                  onTap: () {
                                    setState(() {
                                      _inputText = _textController.text;
                                    });
                                    Navigator.pop(context);
                                  },
                                  child: Container(
                                    padding: const EdgeInsets.symmetric(
                                      horizontal: 16, // 增加按钮的水平内边距
                                      vertical: 8, // 增加按钮的垂直内边距
                                    ),
                                    decoration: BoxDecoration(
                                      color: theme.colorScheme.primary,
                                      borderRadius: BorderRadius.circular(8),
                                      boxShadow: [
                                        // 添加阴影效果
                                        BoxShadow(
                                          color: Colors.black.withOpacity(0.1),
                                          blurRadius: 4,
                                          offset: const Offset(0, 2),
                                        ),
                                      ],
                                    ),
                                    child: Text(
                                      l10n.confirm,
                                      style: GoogleFonts.notoSansSc(
                                        color: Colors.white,
                                        fontSize: 14,
                                        fontWeight: FontWeight.w500,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    final theme = Theme.of(context);
    return Scaffold(
      backgroundColor: theme.scaffoldBackgroundColor,
      appBar: _buildAppBar(l10n, theme),
      body: _buildBody(l10n, theme),
      bottomNavigationBar: _buildBottomBar(theme),
    );
  }

  /// 构建应用栏
  ///
  /// 包含设置按钮、标题和菜单按钮
  PreferredSizeWidget _buildAppBar(AppLocalizations l10n, ThemeData theme) {
    return AppBar(
      backgroundColor: theme.appBarTheme.backgroundColor,
      elevation: 0,
      leading: IconButton(
        icon: Icon(Icons.menu, color: theme.iconTheme.color),
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => const LanguageSettingsScreen(),
            ),
          );
        },
      ),
      title: Text(
        l10n.appTitle,
        style: GoogleFonts.notoSansSc(
          fontSize: 20,
          fontWeight: FontWeight.w500,
          color: theme.textTheme.titleLarge?.color,
        ),
      ),
      centerTitle: true,
      actions: [
        IconButton(
          icon: Icon(Icons.settings, color: theme.iconTheme.color),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => const SettingsScreen(),
              ),
            );
          },
        ),
      ],
    );
  }

  /// 构建主体内容
  ///
  /// 包含输入框、语言切换区域和翻译结果框
  Widget _buildBody(AppLocalizations l10n, ThemeData theme) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 10),
      child: Column(
        children: [
          // 输入框区域
          Expanded(
            flex: 2,
            child: Container(
              width: MediaQuery.of(context).size.width * 0.95,
              margin: const EdgeInsets.symmetric(horizontal: 10),
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: theme.cardColor,
                borderRadius: BorderRadius.circular(12),
                border: Border.all(
                  color: theme.dividerColor,
                  width: 1,
                ),
              ),
              child: SingleChildScrollView(
                child: Text(
                  _inputText.isEmpty ? l10n.inputHint : _inputText,
                  style: TextStyle(
                    color: _inputText.isEmpty
                        ? theme.textTheme.bodySmall?.color
                        : theme.textTheme.bodyLarge?.color,
                    fontSize: 16,
                  ),
                ),
              ),
            ),
          ),

          const SizedBox(height: 10),
          // 语言切换区域
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Consumer<LanguageService>(
              builder: (context, languageService, child) {
                return Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    // 源语言选择
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text(
                          languageService.getLanguageName(
                            context,
                            languageService.currentLocale,
                          ),
                          style: GoogleFonts.notoSansSc(
                            fontSize: 15,
                            color: theme.textTheme.bodyLarge?.color,
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                        const SizedBox(width: 6),
                        Container(
                          padding: const EdgeInsets.all(4),
                          decoration: BoxDecoration(
                            color: Colors.red.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(4),
                          ),
                          child: const Icon(
                            Icons.flag,
                            color: Colors.red,
                            size: 18,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(width: 16),
                    // 语言切换按钮
                    Container(
                      width: 28,
                      height: 28,
                      decoration: BoxDecoration(
                        color: theme.cardColor,
                        borderRadius: BorderRadius.circular(8),
                        border: Border.all(
                          color: theme.colorScheme.primary,
                          width: 2,
                        ),
                      ),
                      child: Stack(
                        alignment: Alignment.center,
                        children: const [
                          Positioned(
                            left: 2,
                            top: 5,
                            child: Icon(
                              Icons.arrow_upward,
                              color: Colors.blue,
                              size: 12,
                            ),
                          ),
                          Positioned(
                            right: 2,
                            bottom: 5,
                            child: Icon(
                              Icons.arrow_downward,
                              color: Colors.blue,
                              size: 12,
                            ),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(width: 16),
                    // 目标语言选择
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Container(
                          padding: const EdgeInsets.all(4),
                          decoration: BoxDecoration(
                            color: Colors.green.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(4),
                          ),
                          child: const Icon(
                            Icons.flag,
                            color: Colors.green,
                            size: 18,
                          ),
                        ),
                        const SizedBox(width: 6),
                        Text(
                          languageService.getLanguageName(
                            context,
                            const Locale('en'),
                          ),
                          style: GoogleFonts.notoSansSc(
                            fontSize: 15,
                            color: theme.textTheme.bodyLarge?.color,
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                      ],
                    ),
                  ],
                );
              },
            ),
          ),
          const SizedBox(height: 10),
          // 翻译结果框
          Expanded(
            flex: 2,
            child: Container(
              width: MediaQuery.of(context).size.width * 0.95,
              margin: const EdgeInsets.symmetric(horizontal: 10),
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: theme.cardColor,
                borderRadius: BorderRadius.circular(12),
                border: Border.all(
                  color: theme.dividerColor,
                  width: 1,
                ),
              ),
              child: SingleChildScrollView(
                child: Text(
                  _translationResult.isEmpty
                      ? l10n.translationResult
                      : _translationResult,
                  style: TextStyle(
                    color: _translationResult.isEmpty
                        ? theme.textTheme.bodySmall?.color
                        : theme.textTheme.bodyLarge?.color,
                    fontSize: 16,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建底部功能按钮栏
  ///
  /// 包含对话模式切换、语言切换、语音输入、相机输入和键盘输入按钮
  Widget _buildBottomBar(ThemeData theme) {
    return BottomAppBar(
      color: theme.bottomAppBarTheme.color,
      child: SizedBox(
        height: 56,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            // 对话模式切换按钮
            GestureDetector(
              onTap: () {
                Navigator.push(
                  context,
                  PageRouteBuilder(
                    pageBuilder: (context, animation, secondaryAnimation) =>
                        const ConversationScreen(),
                    transitionDuration: const Duration(milliseconds: 800),
                    transitionsBuilder:
                        (context, animation, secondaryAnimation, child) {
                      return AnimatedBuilder(
                        animation: animation,
                        child: child,
                        builder: (BuildContext context, Widget? child) {
                          // 3D翻转动画效果
                          final rotate = Tween(begin: math.pi / 2.8, end: 0.0)
                              .animate(CurvedAnimation(
                            parent: animation,
                            curve: Curves.easeOutBack,
                          ));
                          final scale = Tween(begin: 0.8, end: 1.0)
                              .animate(CurvedAnimation(
                            parent: animation,
                            curve: Curves.easeOutBack,
                          ));
                          final opacity = Tween(begin: 0.0, end: 1.0)
                              .animate(CurvedAnimation(
                            parent: animation,
                            curve: const Interval(0.4, 1.0),
                          ));
                          return Transform(
                            alignment: Alignment.center,
                            transform: Matrix4.identity()
                              ..setEntry(3, 2, 0.001)
                              ..rotateX(rotate.value)
                              ..scale(scale.value),
                            child: Opacity(
                              opacity: opacity.value,
                              child: child,
                            ),
                          );
                        },
                      );
                    },
                  ),
                );
              },
              child: SizedBox(
                width: 40,
                height: 40,
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    Positioned(
                      left: 8,
                      top: 8,
                      child: Icon(
                        Icons.arrow_upward,
                        color: theme.iconTheme.color,
                        size: 14,
                      ),
                    ),
                    Positioned(
                      right: 8,
                      bottom: 8,
                      child: Icon(
                        Icons.arrow_downward,
                        color: theme.iconTheme.color,
                        size: 14,
                      ),
                    ),
                  ],
                ),
              ),
            ),
            // 语言切换按钮
            SizedBox(
              width: 40,
              height: 40,
              child: IconButton(
                padding: EdgeInsets.zero,
                icon: Icon(
                  Icons.refresh,
                  color: theme.iconTheme.color,
                  size: 22,
                ),
                onPressed: _clearContent,
              ),
            ),
            // 语音输入按钮
            Container(
              width: 56,
              height: 56,
              decoration: BoxDecoration(
                color: _isListening ? Colors.red : theme.colorScheme.primary,
                shape: BoxShape.circle,
              ),
              child: IconButton(
                icon: Icon(
                  _isListening ? Icons.mic : Icons.mic_none,
                  color: Colors.white,
                  size: 28,
                ),
                onPressed: () {
                  setState(() {
                    _isListening = !_isListening;
                  });
                },
              ),
            ),
            // 相机输入按钮
            SizedBox(
              width: 40,
              height: 40,
              child: IconButton(
                padding: EdgeInsets.zero,
                icon: Icon(
                  Icons.camera_alt,
                  color: theme.iconTheme.color,
                  size: 22,
                ),
                onPressed: () async {
                  final imagePath = await Navigator.push<String>(
                    context,
                    MaterialPageRoute(
                      builder: (context) => const CameraScreen(),
                    ),
                  );

                  if (imagePath != null) {
                    debugPrint('拍摄的照片路径: $imagePath');
                  }
                },
              ),
            ),
            // 键盘输入按钮
            SizedBox(
              width: 40,
              height: 40,
              child: IconButton(
                padding: EdgeInsets.zero,
                icon: Icon(
                  Icons.keyboard,
                  color: theme.iconTheme.color,
                  size: 22,
                ),
                onPressed: _showInputDialog,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
